package com.gs.disk.service.common;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gs.disk.dao.admin.RoleDao;
import com.gs.disk.dao.admin.UserDao;
import com.gs.entity.RoleEntity;
import com.gs.entity.UserEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;

@Service
public class RoleService {

    @Resource
    private RoleDao dao;

    @Resource
    private UserDao userDao;

    /**
     * 角色名列表
     * @param userId 用户id
     * @return
     */
    public List<String> roleNameList(Serializable userId) {
        UserEntity userEntity = userDao.selectById(userId);
        String[] roleIdArr = Optional.ofNullable(userEntity.getRoleIds()).orElse("")
                .split(",");

        List<String> resultRoleList = new LinkedList<>();
        List<RoleEntity> roleEntities = dao.selectBatchIds(Arrays.asList(roleIdArr));
        roleEntities.stream().forEach(r -> resultRoleList.add(r.getRoleName()));
        return resultRoleList;
    }

    /**
     * 角色列表
     * @return
     */
    public List<RoleEntity> roleList() {
        List<RoleEntity> roleEntities = dao.selectList(null);
        return roleEntities;
    }

    /**
     * 统计数据量
     * @return
     */
    public Integer count() {
        return dao.count();
    }

    /**
     * 更新菜单列表
     * @param roleId 角色id
     * @param permissionList 权限列表
     */
    public void updatePermissions(Long roleId, List<String> permissionList) {
        StringJoiner sj = new StringJoiner(",");
        permissionList.stream().forEach(sj::add);

        UpdateWrapper<RoleEntity> wrapper = new UpdateWrapper();
        wrapper.eq("id", roleId);
        wrapper.set("menu_list", sj.toString());
        dao.update(null, wrapper);
    }
}
